# forms.py
import urllib
import time
import os
import sys
import gettext

# ----------------------------------------------------------------

def scriptInputFormWithMessage(version,
                               message,
                               tag,
                               slideList,
                               oldSlide,
                               hideButtons,
                               pathToPublishedHtml,
                               email):
    slides = ""
    tagForURL = urllib.urlencode({'tag':tag,'email':email})
    for num, slide in enumerate(slideList):
        slides += '\n\n<hr>'
        slides += '<a name="slideNumber'+str(num)+'"></a>\n'

        # ------------------------------------
        # Add Slide (before), Change, Delete Buttons
        # ------------------------------------
        if not hideButtons:

            slides += '<button type="button" '
            slides +=         'onClick="window.location='+"'"+"/addSlide"
            slides +=         "?"+tagForURL+"&slideNumber="+str(num)
            slides +=         "#slideNumber"+str(num)+"'"+'">'
            slides +=         'Add slide</button> \n'

            if len(slide[0].strip())>0:
                #show change slide button if slide is shown
                slides += '<button type="button" '
                slides +=         'onClick="window.location='+"'"+"/changeSlide"
                slides +=         "?"+tagForURL+"&slideNumber="+str(num)
                slides +=         "#slideNumber"+str(num)+"'"+'">'
                slides +=         'Change slide</button> \n'

            slides += '<button type="button" '
            slides +=         'onClick="window.location='+"'"+"/deleteSlide"
            slides +=         "?"+tagForURL+"&slideNumber="+str(num)+"&time="+str(time.time())
            slides +=         "#slideNumber"+str(max(0,num-1))+"'"+'">'
            slides +=         'Delete slide</button><br>\n'

        # ------------------------------------------------------------------------
        # Image (or input box for link to image), textarea and submit button
        # ------------------------------------------------------------------------

        if len(slide[0].strip())>0:
            #show slide if link is available
            slides += '<input type="hidden" id="slideSource'+str(num)
            slides +=     '" name="slideSource'+str(num)+'" value="'+slide[0]+'" />\n'
            slides += '<img src="'+slide[0]+'" alt="Slide '+str(num)
            slides +=     '" width="300" height="227" style="border:1px solid black"><br>\n'
            slides += '<textarea  id="textarea'+str(num)+'" name="textarea'+str(num)
            slides +=     '" rows="5" cols="80">'+slide[1]
            slides += '</textarea><br>'
            if not hideButtons:
                slides += '<div id="submit_button">'
                slides += '<input type="submit" value="Submit""/> '
                slides += '<input type="checkbox" name="publishFlag" value="True" /> '
                slides += 'Publish<br></div>'
        else:
            #request link for slide
            slides += 'Link to slide: <input id="slideSource'+str(num)
            slides +=     '" name="slideSource'+str(num)+'" size=80 value="'+oldSlide+'" /><br>'
            slides += '<input type="submit" value="Submit"/> '
            slides += '<input type="checkbox" name="publishFlag" value="True" /> Publish<br>'
            slides += '<textarea  id="textarea'+str(num)+'" name="textarea'+str(num)
            slides +=     '" rows="5" cols="80">'+slide[1]
            slides += '</textarea><br>'


    # ------------------------------------
    # Add Slide (after last) Button
    # ------------------------------------

    slides += '<hr>'
    if not hideButtons:
        slides += '<button type="button" '
        slides +=         'onClick="window.location='+"'"+"/addSlide"
        slides +=         "?"+tagForURL+"&slideNumber="+str(len(slideList))
        slides +=         "#slideNumber"+str(len(slideList))+"'"+'">'
        slides +=         'Add slide</button> '

        newButton = '''<br>
        <button type="button" onClick="window.location='/index'">New Script</button>'''
    else:
        newButton = ""

    viewButton = ""
    if 0<len(pathToPublishedHtml.strip()):
        viewButton = '<button type="button" onClick="window.location='+"'"
        viewButton += 'initView?pathToPublishedHtml='+pathToPublishedHtml.strip()+"'"+'">'
        viewButton += 'View'
        viewButton += '</button> '
        viewButton += '<input type="submit" value="Unpublish"/> '
    viewButton += '''<button type="button" onClick="window.location='/listScripts?email={0}'">List Scripts</button>'''.format(email)
    viewButton += '''<button type="button" onClick="window.location='/deleteScript?'''
    viewButton += tagForURL+"""'">Delete Script</button>"""

    return u'''<html><head>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
        <title>SlideSpeech Authoring</title>
        <style type="text/css">
        form{{font-family:Arial,Helvetica,sans-serif;font-size:80%;}}
        h1{{font-family:Arial,Helvetica,sans-serif;}}
        small{{font-family:Arial,Helvetica,sans-serif;}}
        </style>
        </head><body>
        <center>
        <table><tr><td align="center">
        <img src="static/img/slideSpeechLogo.png" alt="SlideSpeech Authoring"></td></tr>
        <tr><td><i>{1}</i></td></tr>
        <tr><td><form action="submitSlides" method="GET" accept-charset="utf-8">
        <input id="email" name="email" type="hidden" value="{6}">
        Title: <input id="tag" name="tag" size="30" value="{2}"/> {5}
        {3}

        </form>
        {4}
        </td></tr>
        <tr><td><i>{1}</i><br><small>Version {0}<br>
        Text-to-Speech by <a href="http://cereproc.com">CereProc</a></small>
        </td></tr></table></center>
        <hr></body></html>'''.format(version, message, tag, slides, newButton, viewButton, email)

# ----------------------------------------------------------------

def fetchScriptToView(url):
    return '''<html>
        <head>
        <script type="text/javascript">
        function load()
        {{
        window.location = "{0}";
        }}
        </script>
        </head>

        <body onload="load()">
        </body>
        </html>'''.format(url)

# ----------------------------------------------------------------

def getTitle(version, errorMessage, email):
    if 0<len(errorMessage):
        errorMessage = '<br><br><i>'+errorMessage+'</i><br>'
    return u'''<html><head><title>SlideSpeech Authoring</title>
        <style type="text/css">
        form{{font-family:Arial,Helvetica,sans-serif;font-size:80%;}}
        h1{{font-family:Arial,Helvetica,sans-serif;}}
        body{{font-family:Arial,Helvetica,sans-serif;}}
        small{{font-family:Arial,Helvetica,sans-serif;}}
        </style>
        </head>
        <body>
        <center>
        <table><tr><td align="center">
        <img src="static/img/slideSpeechLogo.png" alt="SlideSpeech Authoring"></td></tr>
        <tr><td>
        <form action="fetchSlides" method="GET" accept-charset="utf-8">
        Script Name:<br>
        <input type="text" name="tag" size="40" /><br>
        <input type="submit" value="Submit"/>
        {1}
        </form>
        <br>
        <button type="button" onClick="window.location='/importScript?email={2}'">Import Script</button><br>
        <button type="button" onClick="window.location='/listScripts'">List Scripts</button>
        <br><br>
        <small>Version {0}<br>
        Text-to-Speech by <a href="http://cereproc.com">CereProc</a></small>
        </td></tr></table></center>
        <hr></body></html>'''.format(version, errorMessage, email)

# ----------------------------------------------------------------

def getScript(version, errorMessage, email):
    if 0<len(errorMessage):
        errorMessage = '<br><br><i>'+errorMessage+'</i><br>'
    importSection = ""
    if sys.platform.startswith("win"):
        importSection = u""" <tr><td>
        <H2>Import PowerPoint</H2>

        <form action="uploadPPT" method="post" enctype="multipart/form-data">
        Path to PowerPoint File:<br>
        <input id="email" name="email" type="hidden" value="{0}">
        <input type="file" name="myFile" size="80" /><br />
        <input type="submit" value="Upload"/>
        </form></td></tr>
        """.format(email)
        
    elif not sys.platform.startswith("darwin"):
        importSection = u"""<tr><td>
        <H2>Import Open Document Presentation (.odp)</H2>

        <form action="uploadODP" method="post" enctype="multipart/form-data">
        Path to ODP File:<br>
        <input id="email" name="email" type="hidden" value="{0}">
        <input type="file" name="myFile" size="80" /><br />
        <input type="submit" value="Upload"/>
        </form></td></tr>
        """.format(email)
        
    return u'''<html><head><title>SlideSpeech Authoring</title>
        <style type="text/css">
        form{font-family:Arial,Helvetica,sans-serif;font-size:80%;}
        h1{font-family:Arial,Helvetica,sans-serif;}
        h2{font-family:Arial,Helvetica,sans-serif;}
        small{font-family:Arial,Helvetica,sans-serif;}
        </style></head><body>
        <center>
        <table><tr><td align="center">
        <img src="static/img/slideSpeechLogo.png" alt="SlideSpeech Authoring"></td></tr>
        ''' + \
        importSection + \
        u'''
        <tr><td><H2>Import Script</H2>

        <form action="importSlides" method="GET" accept-charset="utf-8">
        Link to Script File (script.txt) in Dropbox:<br>
        <input type="hidden" name="title" value="" />
        <input type="hidden" name="scriptPath" value="" />
        <input id="email" name="email" type="hidden" value="{2}">
        <input type="text" name="url" size="80" /><br>
        <input type="submit" value="Upload"/>
        </form><br>

        <form action="uploadScript" method="post" enctype="multipart/form-data">
            Title for Script:<br>
            <input type="text" name="title" size="80" /><br>
            Path to Script File (script.txt) on local drive:<br>
            <input type="file" name="myFile" size="80" /><br />
            <input type="submit"  value="Upload"/>
            </form>
            </td></tr>
        {1}
        <br><br>
        <tr><td><small>Version {0}</small>
            </td></tr></table><br>
        <hr></body></html>'''.format(version, errorMessage, email)

# ----------------------------------------------------------------

def getScriptAndEmail(version, errorMessage):
    if 0<len(errorMessage):
        errorMessage = '<br><br><i>'+errorMessage+'</i><br>'
    importSection = ""
    if sys.platform.startswith("win"):
        importSection = u""" <tr><td>
        <H2>PowerPoint Presentation verffentlichen</H2>
        <form action="uploadPPT" method="post" enctype="multipart/form-data">
        <table>
        <tr><td>Pfad zur PowerPoint Datei:</td><td>
        <input type="file" name="myFile" size="60" /></td></tr>
        <tr><td>E-Mail:</td><td>
        <input type="text" name="email" value="jg07024@gmail.com" /></td></tr>
        <tr><td></td><td>
        <input type="submit" value="Upload"/></td></tr>
        </table>
        </form></td></tr>
"""
    elif sys.platform.startswith("darwin"):
        importSection = u"""<tr><td>
        <H2>Publish Your Open Document Presentation (.odp format*)</H2></td></tr>
        <tr><td>Prepare your presentation with text in the speaker notes of each slide.</td></tr>
        <tr><td>Need help? Watch a <a href="http://youtu.be/iE_zsKZEzGM" target="_blank">demo video</a> or
        <a href="static/1330145540.759150/odpName.htm" target="_blank">how-to presentation (4 slides)</a></td></tr>
        <tr><td></td></tr>
        <tr><td>
        <form name="myForm" action="uploadODP" method="post" enctype="multipart/form-data">
        <table>
        <tr><td>ODP File:</td><td>
        <input type="file" name="myFile" size="40" /></td></tr>

        <tr><td>E-Mail:</td><td>
        <input type="text" name="email" size="40" /></td></tr>

        <tr><td></td><td>
        <input type="submit" value="Publish"></td></tr>
        </table>
        </form>
"""
    else:
        importSection = u"""<tr><td>
        <H2>Publish Your Open Document Presentation (.odp format*)</H2></td></tr>
        <tr><td>Prepare your presentation with text in the speaker notes of each slide.</td></tr>
        <tr><td>Need help? Watch a <a href="http://youtu.be/iE_zsKZEzGM" target="_blank">demo video</a></td></tr>
        <tr><td></td></tr>
        <tr><td>
        <form name="myForm" action="uploadODP" method="post" enctype="multipart/form-data">
        <table>
        <tr><td>ODP File:</td><td>
        <input type="file" name="myFile" size="40" /></td></tr>
        
        <tr><td>Title:</td><td>
        <input type="text" name="title" size="40" /></td></tr>
        
        <tr><td>Autho:</td><td>
        <input type="text" name="author" size="40" /></td></tr>
        
        <tr><td>E-Mail:</td><td>
        <input type="text" name="email" size="40" /></td></tr>
        
        <tr><td></td><td>
        <input type="submit" value="Publish"></td></tr>
        </table>
        </form>
"""
    return u'''<html><head><title>SlideSpeech Authoring</title>
        <style type="text/css">
        form{font-family:Arial,Helvetica,sans-serif;font-size:80%;}
        body{font-family:Arial,Helvetica,sans-serif;}
        h1{font-family:Arial,Helvetica,sans-serif;}
        h2{font-family:Arial,Helvetica,sans-serif;}
        small{font-family:Arial,Helvetica,sans-serif;}
        </style>
        <link rel="stylesheet" type="text/css" media="all" href="atbar.css">
        </head><body><?php include('toolbar-launcher.php'); ?>
        <div id="google_translate_element"></div><script>
function googleTranslateElementInit() {
  new google.translate.TranslateElement({
    pageLanguage: 'en'
  }, 'google_translate_element');
}
</script><script src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script><script type="text/javascript">var _kiq = _kiq || [];</script>
<script type="text/javascript" src="//s3.amazonaws.com/ki.js/32933/6pu.js" async="true"></script>
        <center>
        <table><tr><td align="center">
        <img src="static/img/slideSpeechLogo.png" alt="SlideSpeech Authoring"></td></tr>
        {2}
        {1}
        <br><br>
        <tr><td><small>* Kennen Sie das kostenlose open-source Programm <a href="http://www.libreoffice.org/"  target="_blank">LibreOffice</a>?</br></br>
        Version {0}<br>
        Text-to-Speech von <a href="http://cereproc.com">CereProc</a></small></td></tr>
        </table>
        
        <hr>
        <img src="http://chart.apis.google.com/chart?cht=qr&chs=120x120&chld=L&choe=UTF-8&chl=http%3A%2F%2Fslidespeech2012.pagekite.me%2F">
        </body></html>'''.format(version, errorMessage)

# ----------------------------------------------------------------

def listScripts(version, errorMessage, scriptList, publishedScript, tempPath, email):
    scripts= u""
    topButton = u""
    if 10<len(scriptList):
        topButton = u'''<tr><td><button type="button" onClick="window.location='/index'">'''
        topButton += u'''Neues Skript hinzuf gen</button> '''
        topButton += u'''<button type="button" onClick="window.location='/importScript?email={0}'">'''.format(email)
        topButton += u'''Import Skript</button></td></tr>'''
    for script in scriptList:
        tagForURL = urllib.urlencode({'tag':script[SlideSpeechAuthoring.TAG],'email':email})
        scripts += u'<tr>\n  <td>\n'
        scripts += u'<a href="/fetchSlides?'+tagForURL+'">'
        scripts += script[SlideSpeechAuthoring.TAG]
        scripts += u'</a></td>\n  <td>'
        if 0<len(script[SlideSpeechAuthoring.PUBLISHEDTIME]):
            scripts += u'<button type="button" onClick="window.location='+"'"
            scripts += u'initView?'
            scripts += u'pathToPublishedHtml='+script[SlideSpeechAuthoring.PUBLISHEDTIME]+"'"+'">'
            scripts += u'Play'
            scripts += u'</button>'
            scripts += u'</a></td>\n</tr>\n'
        else:
            scripts += u'<button type="button" onClick="window.location='+"'"
            scripts += u'/publishSlidesToHtml?'+tagForURL+"'"+'">'
            scripts += u'Ver ffentlichen'
            scripts += u'</button>'
            scripts += u'</a></td></tr>'
    if 0<len(errorMessage):
        errorMessage = '<br><br><i>'+errorMessage+'</i><br>'
    return u'''<html><head><title>SlideSpeech</title>
        <style type="text/css">
        table{{font-family:Arial,Helvetica,sans-serif;}}
        h1{{font-family:Arial,Helvetica,sans-serif;}}
        h2{{font-family:Arial,Helvetica,sans-serif;}}
        small{{font-family:Arial,Helvetica,sans-serif;}}
        </style></head><body>
        <center>
        <table><tr><td align="center">
        <img src="static/img/slideSpeechLogo.png" alt="SlideSpeech Authoring"></td></tr>
        <tr><td align="center">
        <b>Skript Liste</b><br>
        <small>{4}</small><br>
        <hr>
        </td></tr>
        {3}
        <tr><td><table>
        {2}
        </table><hr></td></tr>
        <tr><td><button type="button" onClick="window.location='/index'">Neues Skript hinzuf gen</button></td></tr>
        <tr><td><button type="button" onClick="window.location='/importScript?email={4}'">Import Skript</button></td></tr>
        <tr><td><small>Version {0}<br>
        Text-to-Speech von <a href="http://cereproc.com">CereProc</a></small></td></tr>
        </table>
        <hr></body></html>'''.format(version, errorMessage, scripts, topButton, email)
        

def uploadPresentationFile(version, language, errorMessage):
    """Display the 'Upload presentation file' form."""
    from jinja2 import Environment, FileSystemLoader
    env = Environment(loader=FileSystemLoader('templates'), extensions=['jinja2.ext.i18n'])    
    domain = 'slidespeech'
    try:
        trans = gettext.translation(domain, os.path.join(os.getcwd(), 'locale'), [language])
    except IOError:
        # This probably means that there is no .mo file.
        # FIXME: This needs to be generated during installation
        trans = gettext.NullTranslations()

    env.install_gettext_translations(trans)
    template = env.get_template('uploadPresentationFile.html')
    return template.render(LANGUAGE=language, errorMessage=errorMessage, version=version)
